/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.workflow.price;

import com.bifrost.entity.Order;
import com.bifrost.exception.PricingException;
import com.bifrost.workflow.BaseActivity;
import com.bifrost.workflow.ProcessContext;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @author joewee
 * @version 1.0.0
 * @Date 2017/11/14 13:55
 */
@Component("totalActivity")
public class TotalActivity extends BaseActivity<ProcessContext<Order>> {
    public static final int ORDER = 9000;

    public TotalActivity() {
        setOrder(ORDER);
    }

    @Override
    public ProcessContext<Order> execute(ProcessContext<Order> context) throws Exception {
        Order order = context.getSeedData();
        BigDecimal orderTotal = BigDecimal.ZERO;
        orderTotal = orderTotal.add(order.getSubTotal());
        orderTotal = orderTotal.add(order.getTotalService());
        orderTotal = orderTotal.add(order.getTotalShippingFee());
        if (orderTotal.compareTo(BigDecimal.ZERO) <= 0 || orderTotal.compareTo(order.getTotalOffer()) < 0) {
            throw new PricingException("订单金额异常");
        } else {
            orderTotal = orderTotal.subtract(order.getTotalOffer());
        }
        BigDecimal bonusPoints = BigDecimal.valueOf(order.getBonusPointsUsed().intValue());
        if (orderTotal.compareTo(bonusPoints) < 0) {
            bonusPoints = orderTotal;
            order.setBonusPointsUsed(orderTotal.toBigInteger());
        }
        orderTotal = orderTotal.subtract(bonusPoints);
        if (orderTotal.compareTo(BigDecimal.ZERO) < 0) {
            throw new PricingException("订单价格异常");
        }
        order.setOrderTotal(orderTotal);
        context.setSeedData(order);
        return context;
    }
}
